package com.web.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

import com.web.servlet.bean.GamePlayerInfo;
import com.web.servlet.dao.IGamePlayerInfoDao;
import com.web.servlet.dao.impl.GamePlayerInfoDaoImpl;
import com.web.servlet.db.GameDaoImpl;
import com.web.servlet.db.IGameDao;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.google.gson.JsonObject;
import com.web.servlet.bean.Player;
import com.web.servlet.bean.RedisKey;
import com.web.servlet.bean.UserInfo;
import com.web.servlet.dao.DBConnect;
import com.web.servlet.manager.DaoManager;
import com.web.servlet.manager.RedisManager;
import com.web.servlet.utils.RedisHelper;

import net.sf.json.JSONObject;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 965679984515166855L;

	public LoginServlet() {
		super();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		String userName = null;//request.getParameter("userName");
		String userPassword = null;//request.getParameter("userPassword");
		String channel =null ;//request.getParameter("c");//渠道ID
		String openid =request.getParameter("userAccount");//openid(/IMSI)
		String headURl = null;
		int sex = 0;
		String nickName = "";
		System.out.println(request.getParameterMap().keySet().size());
		InputStream is= null; 
		String contentStr="";     
		try {
			is = request.getInputStream();
			contentStr = IOUtils.toString(is, "utf-8");
		} catch (IOException e) {
			e.printStackTrace();

		}

		JSONObject parJson =JSONObject.fromObject(contentStr);
		openid = parJson.getString("userAccount");
		headURl = parJson.getString("headUrl");
		if(null != parJson.get("sex")){
            sex = parJson.getInt("sex");
        }
        if(null != parJson.get("userName")){
            nickName  = parJson.getString("userName");
        }else{
            nickName = openid;
        }



		userName = openid;
		userPassword = "123456";
       /* Random random=new Random();//定义随机类intresult=random.nextInt(10);
        openid = String.valueOf(random.nextInt(999999)+"kkkkk") ;
        userName = openid;*/
	    if(userName!=null && userPassword!=null)
	    {	
	    	//先检查是否存在redis中
	    	String userinfoString = RedisManager.getRedis().hget(RedisKey.USERINFOACCOUNT, userName);
			GamePlayerInfo daoPlayer = null;
			IGamePlayerInfoDao dao = null;
			if(null == userinfoString){//如果redis不存在检查db
				dao = new GamePlayerInfoDaoImpl();
				daoPlayer = dao.getGamePlayerInfoByAccount(openid);
			}
	    	JsonObject loginJson  = new JsonObject();
	    	if(null == userinfoString && null == daoPlayer){//不存在注册
				if(null == dao){
					dao = new GamePlayerInfoDaoImpl();
				}
				userinfoString = addGamePlayer( dao, userName, openid, userPassword,nickName,headURl,sex);
	    	}
	    	
	    	
	    	 
	    	if(null != userinfoString){
	    		JSONObject userJson = JSONObject.fromObject(userinfoString);
	    		loginJson.addProperty("platform", "ios");// 平台
	    		loginJson.addProperty("region", "hunan");// 地区
	    		loginJson.addProperty("channel", "10000");// 渠道
	    		loginJson.addProperty("ver", "1.0.0.0");// 版本号
	    		loginJson.addProperty("squ", "1");// 序号
	    		loginJson.addProperty("timestamp", "0");// 时间戳(防止别人拦截请求然后伪装把服务器资源耗尽)

	    		loginJson.addProperty("uid", String.valueOf(userJson.get("playerID"))  );// 玩家唯一id(上次登陆也算)
	    		loginJson.addProperty("cid", "01");// 玩家地区id
	    		loginJson.addProperty("token", String.valueOf( userJson.get("loginToken")));// 登录token
	    		loginJson.addProperty("userAccount", String.valueOf( userJson.get("userAccount")));// 账号  TODO 需要屏蔽
				loginJson.addProperty("playerHeadUrl", String.valueOf( userJson.get("playerHeadUrl")));// 头像字段
				loginJson.addProperty("sex", String.valueOf( userJson.get("sex")));// 性别
				loginJson.addProperty("diamond",userJson.getInt("diamond"));//赠送钻石
                loginJson.addProperty("nickName",userJson.getString("nickName"));//昵称
	    		out.print(loginJson.toString());
	    	}else{
	    		loginFail(out);
	    	}
	    }
	    else
	    {
	    	loginFail(out);
	    }
		out.flush();
		out.close();
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}
	

	
	
	private void loginFail(PrintWriter out)
	{
		Document document = DocumentHelper.createDocument();
    	Element rootElement = document.addElement("user");
    	rootElement.addAttribute("st", "false");
    	rootElement.addAttribute("dc", "用户名或者密码不对");
    	out.print(document.asXML());
		
	}


	/**
	 * db添加GamePlayer
	 * @param dao
	 * @param userName
	 * @param userPassword
	 */
	public GamePlayerInfo  addGamePlayerToDB(IGamePlayerInfoDao dao,String userName,String userPassword,String nickName,String head_url,int sex){
		GamePlayerInfo info = new GamePlayerInfo();
		info.setAccount(userName);
		info.setPassWord(userPassword);
		info.setPlayer_name(userName);
        info.setPlayer_name(nickName);
        info.setHead_url(head_url);
        info.setSex(sex);
		info.setDiamond(9);//设置初始钻石数量
		dao.addGamePlayerInfo(info);
		return info;
	}
	public String addGamePlayerToRedis(GamePlayerInfo playerInfo ){
		long uid = playerInfo.getPlayer_index();//RedisManager.getRedis().incr(RedisKey.USERIDINRC);
		//channel 添加渠道信息
		JSONObject userJson  =new JSONObject();
		userJson.put("userName", playerInfo.getAccount());
		userJson.put("openid", playerInfo.getAccount());
		userJson.put("userid", uid);
		userJson.put("playerID", uid);
		userJson.put("playerIndex", uid);
		userJson.put("nickName", playerInfo.getPlayer_name());
		userJson.put("userAccount", playerInfo.getAccount());
		userJson.put("loginToken", playerInfo.getAccount()+uid);
		userJson.put("playerHeadUrl", playerInfo.getHead_url());// 头像字段
		userJson.put("sex", playerInfo.getSex());// 性别
		userJson.put("diamond",playerInfo.getDiamond());
		RedisManager.getRedis().hset(RedisKey.USERINFOACCOUNT, playerInfo.getAccount(), userJson.toString());
		RedisManager.getRedis().hset(RedisKey.USERINFOACCOUNT, String.valueOf(uid), userJson.toString());
		return userJson.toString();
	}
	public String addGamePlayer(IGamePlayerInfoDao dao,String userName,String openid,String userPassword,String nickName,String head_url,int sex){
		GamePlayerInfo playerInfo  = addGamePlayerToDB(dao, userName, userPassword, nickName, head_url, sex);
		return addGamePlayerToRedis(playerInfo);
	}
}
